import {
  Controller,
  Post,
  Body,
  BadRequestException,
  Delete,
  Param,
  Patch,
  UseGuards,
  Get,
  Query,
} from '@nestjs/common';
import { CredentialsDto } from 'src/dto/credentials.dto';
import { StaffsService } from './staffs.service';
import { Identity } from 'src/schemas/staff/staff.interface';
import { JwtAuthGuard } from 'src/guards/jwt-auth.guard';
import { FindDataDto } from 'src/dto/find-data.dto';
import { StaffDto } from 'src/dto/staff.dto';

@UseGuards(JwtAuthGuard)
@Controller('staffs')
export class StaffsController {
  constructor(private readonly staffsService: StaffsService) {}

  /**
   * 创建一个员工管理员
   * @param credentialsDto 凭据
   */
  @Post('admin')
  async createStaffAdmin(@Body() credentialsDto: CredentialsDto) {
    return await this.createIdentityStaff(credentialsDto, Identity.StaffAdmin);
  }

  /**
   * 创建一个身份员工
   * @param credentialsDto 凭据
   * @param identity 身份
   */
  @Post()
  async createIdentityStaff(
    @Body() credentialsDto: CredentialsDto,
    identity: Identity,
  ) {
    // 查找员工
    const staff = await this.staffsService.findStaffByAccount(
      credentialsDto.account,
    );

    // 判断用户是否注册
    if (staff) {
      throw new BadRequestException('请使用此账号登录', '员工管理员已经存在');
    }

    // 如果没有传递身份，则默认为员工
    if (identity === undefined) {
      return await this.staffsService.createIdentityStaff(
        credentialsDto,
        Identity.Staff,
      );
    } else {
      return await this.staffsService.createIdentityStaff(
        credentialsDto,
        identity,
      );
    }
  }

  /**
   * 删除一个员工
   * @param _id 员工 _id
   */
  @Delete(':_id')
  async deleteStaff(@Param('_id') _id: string) {
    await this.staffsService.deleteById(_id);
  }

  /**
   * 更新一个员工的密码
   * @param account 账号
   * @param password 密码
   */
  @Patch(':_id')
  async updateStaffPassword(
    @Param('_id') _id: string,
    @Body('password') newPassword: string,
  ) {
    await this.staffsService.updatePasswordById( _id, newPassword );
  }

  /**
   * 查询一些员工
   * @param pageIndex 页码
   * @param pageSize 页大小
   */
  @Get()
  async findStaffs(
    @Query('pageIndex') pageIndex: number,
    @Query('pageSize') pageSize: number,
  ) {
    const data = await this.staffsService.find({ pageIndex, pageSize });
    const total = await this.staffsService.count();
    return {
      total,
      pageIndex,
      pageSize,
      data,
    } as FindDataDto<StaffDto>;
  }
}
